import net.sf.javaml.classification.AbstractClassifier;
import net.sf.javaml.core.Dataset;
import net.sf.javaml.core.Instance;

import java.util.HashMap;

public class Bayes extends AbstractClassifier {

	Dataset training;

    HashMap<Object, HashMap<Integer,Double>> wordProbs = new HashMap<Object, HashMap<Integer,Double>>();

    @Override
    public void buildClassifier(Dataset data) {

        training = data;
        HashMap<Integer, Integer> classDistribution = new HashMap<Integer, Integer>();

        for(int i = 0; i < training.size(); i++) {
            classDistribution.put(i, 0);
        }

        int j = 0;

        for(Object o : training.classes()) {
            wordProbs.put(o, new HashMap<Integer, Double>());
            for(int i = 0; i < training.get(0).values().size(); i++) {
                //System.out.println(i);
                wordProbs.get(o).put(i, 0.0);
            }

            for(Instance i : training) {
                if(i.classValue().equals(o)) {
                    classDistribution.put(j, classDistribution.get(j) + 1);
                }

            }
            j++;
        }
        //System.out.println("hej0");
        j = 0;
        for(Object o : training.classes()) {
            //System.out.println("hej");
            for(Instance inst : training) {
                if(inst.classValue().equals(o)) {
                    for(int i = 0; i < inst.noAttributes(); i++) {
                        if(inst.value(i) > 0) {
                            Double d = wordProbs.get(o).get(i);
                            double temp = classDistribution.get(j);
                            wordProbs.get(o).put(i, d + inst.value(i));
                        }
                    }
                }
            }
            j++;
        }

        //System.out.println("hej1");
    }
    @Override
	public Object classify(Instance i) {
        //System.out.println("hej2");
        Object prediction = training.classes().first();
        double max = 0;


        for(Object o : training.classes()) {
            double product = 1;
            int j = 0;
            for(Double d : i.values()) {
                //System.out.println(wordProbs.get(o).get(j));
                Double prob = wordProbs.get(o).get(j);
                if(prob == null) {
                    System.out.println("unll");
                }
                if(d > 0) {
                    product = prob * product;
                }
                j++;
            }
            //System.out.println(o + " " + product);
            if(product > max) {
                max = product;
                prediction = o;
            }
        }
        //prediction = training.classes().first();
        //System.out.println(prediction);
        return prediction;
	}
	
	



}
